<script setup lang="ts" name="CkIcon">
import type { PropType } from 'vue'
import { getIconList } from './utils'
import { propTypes } from '@/utils/propTypes'
type iconType = {
	type:string;
	key:string;
	value:string;
}
const props = defineProps({
  icon: {
      type: String,
      required: true
    },
    // icon color
    color: propTypes.string,
    // icon size
    size: {
      type: [String, Number] as PropType<string | number>,
      default: 16
    },
    // icon class
    className: {
      type: String,
      default: () => ''
    }
})

const getIconStyle = computed(() => {
  return {
    fontSize: `${props.size}`.replace(/px/, '') + 'px',
    color: props.color
  }
})

const iconInfo: any = computed(():boolean|iconType => {
  return getSvgIcon(props.icon)
})

const svgClass = computed((): string => {
  if (props.className) {
    return 'svg-icon ' + props.className
  } else {
    return 'svg-icon'
  }
})

const getSvgIcon = (iconName:string):boolean|iconType => {
  const iconList:Array<iconType> = getIconList()
  if (iconName.indexOf(':') !== -1) {
    const iconType = iconName.split(':')[0]
    const iconKey = iconName.split(':')[1]
    const iconData = iconList.filter((item:iconType) => {
      return item.type === iconType && item.key === iconKey
    })[0]
    if (iconData) {
      return iconData
    } else {
      return false
    }
  } else {
    return false
  }
}

const valueIsBoolean = (val:any):val is boolean => {
  return typeof val === 'boolean'
}
</script>

<template>
  <el-icon v-if="iconInfo" :style="getIconStyle">
    <component :is="!valueIsBoolean(iconInfo)&&iconInfo.value" :class="svgClass"></component>
  </el-icon>
</template>

<style scoped lang="scss">
.svg-icon {
  width: 1em;
  height: 1em;
  overflow: hidden;
  vertical-align: middle;
  fill: currentcolor;
}
</style>
